package com.dingjian.framework.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.dingjian.base.common.Pagination;
import com.dingjian.base.dao.QueryExecutor;
import com.dingjian.base.util.StringUtils;
import com.dingjian.basedata.org.model.Org;
import com.dingjian.basedata.org.model.Position;
import com.dingjian.basedata.org.service.OrgService;
import com.dingjian.basedata.org.service.PositionService;
import com.dingjian.basedata.person.enums.UserStatusEnum;
import com.dingjian.basedata.person.model.Person;
import com.dingjian.basedata.person.model.PersonPosition;
import com.dingjian.basedata.util.SystemUtil;
import com.dingjian.framework.base.controller.BaseController;
import com.dingjian.permission.util.SecurityUtil;

@Controller
public class LoginController extends BaseController {
	@Resource(name="queryExecutor")
	protected QueryExecutor queryExecutor;
	
	@RequestMapping(value="login")
	public String login(ModelMap model,Person person,HttpServletResponse response) throws ServletException, IOException{
		if(person!=null && StringUtils.isEmpty(person.getUserName())){
			return "framework/login";
		}
		Map<String,Object> param = new HashMap<String, Object>();
		param.put("userName", person.getUserName());
		param.put("password", SecurityUtil.encryptPassword(person.getPassword()));
		List<Person> persons = queryExecutor.execQuery("com.dingjian.basedata.person.dao.PersonDao.loginUser", new Pagination<Person>(), param).getItems();
		if(persons == null || persons.size()==0){
			model.put("msg", "用户名或密码错误");
			model.put("userName", person.getUserName());
			return "framework/login";
		}
		if(!UserStatusEnum.ENABLE.equals(persons.get(0).getStatus())){
			model.put("msg", "该用户未启用或己冻结,请联系管理员");
			model.put("userName", person.getUserName());
			return "framework/login";
		}
		initLoginUserInfo(persons.get(0));
		
		String workbench = "simple";
		if(!StringUtils.isEmpty(getString("workbench"))){
			workbench = getString("workbench");
		}
		getSession().setAttribute("workbench", workbench);
		HttpServletRequest request = getRequest();
		String port = request.getLocalPort()==80?"":":"+request.getLocalPort();
		String path = request.getScheme()+"://"+request.getServerName()+port+request.getContextPath()+"/workbench";
		response.sendRedirect(path);
		return null;
	}
	
	@RequestMapping(value="ajaxLoginPage")
	public String ajaxLoginPage(){
		return "framework/ajaxLoginPage";
	}
	
	@RequestMapping(value="ajaxLogin")
	public void ajaxLogin(Person person,HttpServletResponse response) throws ServletException, IOException{
		if(person!=null && StringUtils.isEmpty(person.getUserName())){
			getOutputMsg().put("MSG", "用户名或密码错误");
			getOutputMsg().put("STATE", "FAIL");
		}
		Map<String,Object> param = new HashMap<String, Object>();
		param.put("userName", person.getUserName());
		param.put("password", SecurityUtil.encryptPassword(person.getPassword()));
		List<Person> persons = queryExecutor.execQuery("com.dingjian.basedata.person.dao.PersonDao.loginUser", new Pagination<Person>(), param).getItems();
		if(persons == null || persons.size()==0){
			getOutputMsg().put("STATE", "FAIL");
			getOutputMsg().put("MSG", "用户名或密码错误");
		}
		if(!UserStatusEnum.ENABLE.equals(persons.get(0).getStatus())){
			getOutputMsg().put("STATE", "FAIL");
			getOutputMsg().put("MSG", "该用户未启用或己冻结,请联系管理员");
		}
		initLoginUserInfo(persons.get(0));
		getOutputMsg().put("STATE", "SUCCESS");
		outPrint(response, JSONObject.fromObject(getOutputMsg()));
	}
	
	@RequestMapping(value="logout")
	public String logout(){
		getSession().invalidate();
		return "framework/login";
	}
	
	@Autowired
	private OrgService orgService;
	@Autowired
	private PositionService positionService;
	
	private void initLoginUserInfo(Person person){
		SystemUtil.setCurrentUser(person);
		getSession().setAttribute("LOGIN-USER", person);
		Map<String,Object> param = new HashMap<String, Object>();
		param.put("person", person.getId());
		param.put("primary", 1);
		List<PersonPosition> pps = queryExecutor.execQuery("com.dingjian.basedata.person.dao.PersonPositionDao.select", param, PersonPosition.class);
		if(pps.size()>0){
			Org org = orgService.getEntityById(pps.get(0).getPosition().getOrg().getId());
			Position position = positionService.getEntityById(pps.get(0).getPosition().getId());
			if(org.getControlUnit()!=null){
				Org cu = orgService.getEntityById(org.getControlUnit().getId());
				getSession().setAttribute("CURRENT-CU", cu);
			}
			getSession().setAttribute("CURRENT-POSITION", position);
			getSession().setAttribute("CURRENT-ORG", org);
		}
	}
}
